package com.example.test.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.test.common.P;
import com.example.test.domain.Book;
import com.example.test.service.Empoyeeservice;
import com.example.test.domain.Empoyee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/empoyee")
public class EmpoyeeController {
    @Autowired
    private Empoyeeservice service;
    @PostMapping("/login")
    public P<Empoyee> login(HttpServletRequest request, @RequestBody Empoyee empoyee){
        LambdaQueryWrapper<Empoyee> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Empoyee::getName,empoyee.getName());
        Empoyee user=service.getOne(wrapper);
//        System.out.println(empoyee);
        if(user==null){
            return P.error("登陆失败");
        }
        if(user.getPassword().equals(empoyee.getPassword())){
            request.getSession().setAttribute("empoyee",user.getId());
            return P.success(user);
        }
        return P.error("密码错误");
    }
    @PostMapping("/logout")
    public P<String> logout(HttpServletRequest request, @RequestBody Empoyee empoyee){
        //清除session的id;
        request.getSession().removeAttribute("empoyee");
        return P.success("退出成功");
    }
    @PostMapping("/getallempoyee")
    public P<List<Empoyee>> getallempoyee(){
        List<Empoyee> list = service.list();
        return P.success(list);
    }
    @PostMapping("/deleteempoyee")
    public P<String> deletebook(@RequestBody Empoyee empoyee){
        boolean b = service.removeById(empoyee.getId());
        if(b){
            return P.success("删除成功！");
        }
        return P.error("删除失败");
    }
    @PostMapping("/updateempoyee")
    public P<String> updateempoyee(@RequestBody Empoyee empoyee){
        LambdaQueryWrapper<Empoyee> wrapper=new LambdaQueryWrapper();
        wrapper.eq(Empoyee::getName,empoyee.getName());
        Empoyee one = service.getOne(wrapper);
        if(one==null){//为新增
            service.save(empoyee);
//            log.info("增加成功");
            return P.success("增加成功");
        }
        else {
            service.updateById(empoyee);
//            log.info("修改成功");
            return P.success("修改成功");
        }
    }
    @PostMapping("/search")
    public P<List<Empoyee>> search(@RequestBody Empoyee empoyee) {
//        System.out.println(empoyee);
        LambdaQueryWrapper<Empoyee> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(Empoyee::getRealname,empoyee.getRealname());
        List<Empoyee> list = service.list(wrapper);
        return P.success(list);
    }

}
